﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Permission;
using B.S.BasicData.Domain.Entity;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.Permission
{
    public class AddRolePermissionHandler : IRequestHandler<AddRolePermissionCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RolePermissionModel> _permissionRepository;
        private readonly IMapper _mapper;

        public AddRolePermissionHandler(IBaseRepository<RolePermissionModel> permissionRepository, IMapper mapper)
        {
            _permissionRepository = permissionRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 角色权限添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(AddRolePermissionCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            //先判断已有权限进行删除
            var permission =_permissionRepository.GetAll().Where(p=>p.RId==request.RId).ToList();
            if(permission.Any() )
            {
                _permissionRepository.DeleteRange(permission);
            }

            //新增权限
            if(!string.IsNullOrEmpty(request.MId))
            {
                var list = request.MId.Split(',').Select(x => Convert.ToInt32(x)).ToList();
                foreach( var item in list)
                {
                    RolePermissionModel model = new RolePermissionModel();
                    model.MId = item;
                    model.RId = request.RId;
                    _permissionRepository.Add(model);
                }
                    result.Code = StatusEnum.OK;
                    result.Data = 1;
                    result.Message = "添加成功";
                    return Task.FromResult(result);
            }
            result.Code = StatusEnum.OK;
            result.Data = 0;
            result.Message = "清除成功";
            return Task.FromResult(result);
        }
    }
}
